import {onUnmounted,nextTick} from 'vue'
import * as echarts from 'echarts'
import { useResize } from './useResize.js'
import {throttle} from 'lodash-es'//js函数功能库

export function useChart(
    elRef//echarts 对应的容器的结构
){
    //初始节点
    let chartsInstanceRef = null
    let resizeFn = resize
    const debounceResize = throttle(resizeFn,200)
    resizeFn = debounceResize
    //完成节流 resize
    useResize(resizeFn)

    // useResize 中的handlerFn
    function resize(){
        if(!chartsInstanceRef){
            return
        }
        chartsInstanceRef.resize()
    }

    //初始化echarts
    function init(){
        chartsInstanceRef = echarts.init(elRef.value)
    }

    const setOptions = (options)=>{
        //初始化
        init()
        //使用nextTick  保证DOM节点处于是出于最新状态
        nextTick(()=>{
            chartsInstanceRef.setOption(options)
        })
    }

    //卸载组件 防止内存丢失
    onUnmounted(()=>{
        if(!chartsInstanceRef){
            return
        }
        chartsInstanceRef.dispose()//释放内存
        chartsInstanceRef = null
    })

    return {
        setOptions
    }
}